<?php

abstract class Lin_Db_Table 
{
	public $db;

	public function __construct()
	{
		$this->db = Lin_Db::getInstance();
	}
	
	/*
	 * 通过key获取值，以一唯数据的形式返回。
	 */
	public function get($key)
	{
		$sql = "SELECT * FROM `{$this->_table}` WHERE `{$this->_key}` = '{$key}'";
		return $this->db->fetchFirst($sql);
	}
	
	/*
	 * 通过查询条件获取数据集
	 */
	public function getAll($where = '1', $fields = array(), $id = '')
	{
		$sql = '';
		$fieldStr = '*';
		if (is_array($fields) && count($fields) > 0)
		{
			foreach ($fields as $key => $val)
			{
				$fields[$key] = '`' . $val . '`';
			}
			
			$fieldStr = implode(',', $fields);
		}
		
		$sql = "SELECT {$fieldStr} FROM `{$this->_table}` WHERE {$where}";
		return $this->db->fetchAll($sql, $id);		
	}
	
	/*
	 * 根据条件值进行更新
	 */
	public function setAll($where, $data)
	{
		$sql = '';
		$fields = array();
		$fieldsStr = '';
		if (!is_array($data))
		{
			throw new Exception('$data is not a array.');
		}
		foreach ($data as $key => $val)
		{
			$val = str_replace("'", "\'", $val);
			$fields[] = "`{$key}` = '{$val}'";
		}
		
		$fieldsStr = implode(',', $fields);
		
		$sql = "UPDATE `{$this->_table}` SET {$fieldsStr} WHERE {$where}";
		return $this->db->query($sql);
	}
	
	/*
	 * 根据key值进行更新
	 */
	public function set($key, $data)
	{
		return $this->setAll("`$this->_key` = '{$key}'", $data);
	}
	
	
	
	/*
	 * 保存数据
	 */
	public function put($data)
	{
		if (!is_array($data) || count($data) == 0)
		{
			throw new Exception('$data is not a array or empty.');
		}	

		$fieldStr = '';
		$fields = array();
		$valStr = '';
		$vals = array();
		
		foreach ($data as $key => $val)
		{
			$fields[] = '`' . $key . '`';
			$val = str_replace("'", "\'", $val);
			$vals[] = "'{$val}'";
 		}
		
		$fieldStr = implode(',', $fields);
		$valStr = implode(',', $vals);
		
		$sql = "INSERT INTO `{$this->_table}` ({$fieldStr}) VALUE ({$valStr})";
		return $this->db->query($sql);
	}
	
	/*
	 * 根据条件删除数据
	 */
	public function removeAll($where)
	{
		$sql = "DELETE FROM `{$this->_table}` WHERE {$where}";
		return $this->db->query($sql);
	}
	
	/*
	 * 根据主键删除数据
	 */
	public function remove($key)
	{
		$where = "`{$this->_key}` = '{$key}'";
		return $this->removeAll($where);
	}
}